<template>
    <div style="-webkit-app-region: drag;">
        <div class="container">
            <el-card class="card">
                <div>
                    <h1>登录-智慧团建</h1>
                    <el-form
                        style="-webkit-app-region: no-drag;"
                        ref="form"
                        label-width="80px"
                    >
                        <el-form-item label="您的账号">
                            <el-input v-model="form.account"></el-input>
                        </el-form-item>
                        <el-form-item label="您的账号">
                            <el-input v-model="form.password" type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="验证码">
                            <div class="xx-code">
                                <img
                                    @click = "changeCode"
                                    ref="code"
                                    style="margin-right: 10px;cursor: pointer;"
                                    src=""
                                />
                                <el-input v-model="form.code"></el-input>
                            </div>
                        </el-form-item>
                        <div>
                            <el-button type="primary" @click="login"
                                >立即登录</el-button
                            >
                        </div>
                    </el-form>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script>
import fs from 'fs'
import { remote } from 'electron'
import path from 'path'
import https from 'https'
export default {
    data() {
        return {
            form: {}
        }
    },
    mounted() {
        this.$refs.code.src = 'https://tuanapi.12355.net/login/loginValidCode?t=' + new Date().getTime()
        // this.getCode()
        this.readConfig()
    },
    methods: {
        changeCode() {
            this.$refs.code.src = 'https://tuanapi.12355.net/login/loginValidCode?t=' + new Date().getTime()
        },
        readConfig() {
            // 读取配置文件，变量config的类型是Object类型
            let config = null
            const filePath = path.join(remote.app.getPath('userData'), 'config.json')
            console.log(filePath)
            try {
                config = JSON.parse(fs.readFileSync(filePath).toString())
                this.form = config
                console.log(this.$route.params.logout)
                if (this.$route.params.logout) {
                    return
                }
                this.login()
            } catch (err) {
                console.log('没有默认账号密码。')
            }
            console.log(config)
        },
        saveConfig() {
            try {
                const filePath = path.join(remote.app.getPath('userData'), 'config.json')
                fs.writeFileSync(filePath, JSON.stringify(this.form))
                // 文件写入成功。
            } catch (err) {
                console.error(err)
            }
        },
        async login() {
            const res = await this.login_go(this.form.account, this.form.password, this.form.code, 1627653449003)
            console.log(res)
            if (res.status == 'OK') {
                this.saveConfig()
                const oid = await this.getOid(this.codeCookie)
                this.$store.commit('setOid', oid)
                console.log(oid)
                const token = await this.getYoungToken(this.codeCookie)
                this.$store.commit('setToken', token)
                console.log(token)
                this.$router.push('/admin/status')
            } else {
                this.$alert(res.msg, '产生了一段爱情', {
                    confirmButtonText: '确定'
                })
                this.changeCode()
            }
        },
        async login_go(userName, password, loginValidCode, t = 1627653449003) {
            const res = await fetch(`https://tuanapi.12355.net/login/adminLogin?userName=${userName}&password=${password}&loginValidCode=${loginValidCode}&_=${t}`, {
                headers: {
                    accept: 'application/json, text/javascript, */* q=0.01',
                    'accept-language': 'zh-CN,zhq=0.9,enq=0.8,en-GBq=0.7,en-USq=0.6',
                    'cache-control': 'no-cache',
                    pragma: 'no-cache',
                    'sec-ch-ua': '"Chromium"v="92", " Not ABrand"v="99", "Microsoft Edge"v="92"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-site'
                },
                referrer: 'https://tuan.12355.net/',
                referrerPolicy: 'strict-origin-when-cross-origin',
                body: null,
                method: 'GET',
                mode: 'no-cors',
                credentials: 'include'
            })
            const temp = await res.json()
            return temp
        },
        async getCode(t = 1627653449003) {
            const res = await new Promise((resolve, reject) => {
                https.get(`https://tuanapi.12355.net/login/loginValidCode?t=${t}`, (req, res) => {
                    let imgData = ''
                    req.setEncoding('base64')
                    req.on('data', function(chunk) {
                        imgData += chunk
                    })
                    req.on('end', function() {
                        const code = req.headers['set-cookie'][0].split(';')[0]
                        resolve({ imgData, code })
                    })
                })
            })
            console.log(res)
            this.$refs.code.src = 'data:image/jpeg;base64,' + res.imgData
            this.codeCookie = res.code
            this.$store.commit('setCookie', res.code)
        },
        async getOid(cookie) {
            const res = await fetch('https://tuanapi.12355.net/login/getSessionAccount', {
                headers: {
                    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                    'cache-control': 'no-cache',
                    pragma: 'no-cache',
                    'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Microsoft Edge";v="92"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-fetch-dest': 'document',
                    'sec-fetch-mode': 'navigate',
                    'sec-fetch-site': 'none',
                    'sec-fetch-user': '?1',
                    'upgrade-insecure-requests': '1',
                    Cookie: cookie
                },
                referrerPolicy: 'strict-origin-when-cross-origin',
                body: null,
                method: 'GET',
                mode: 'cors',
                credentials: 'include'
            })
            const temp = await res.json()
            this.$store.commit('setFullName', temp.account.fullName)
            return temp.account.oid
        },
        async getYoungToken(cookie) {
            const res = await fetch('https://tuanapi.12355.net/questionnaire/getPcYouthLearningUrl?_=1626355745781', {
                headers: {
                    accept: 'application/json, text/javascript, */*; q=0.01',
                    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                    'cache-control': 'no-cache',
                    pragma: 'no-cache',
                    'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Microsoft Edge";v="92"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-site',
                    Cookie: cookie
                },
                referrer: 'https://tuan.12355.net/',
                referrerPolicy: 'strict-origin-when-cross-origin',
                body: null,
                method: 'GET',
                mode: 'cors',
                credentials: 'include'
            })
            const temp = await res.json()
            return temp.youthLearningUrl.split('zhtjToken=')[1]
        }
    }
}
</script>

<style lang="less" scoped>
.container {
    background-color: rgba(240, 248, 255, 0);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 500px;
}
.card {
    width: 400px;
    .xx-code {
        display: flex;
        flex-direction: row;
    }
}
</style>
